<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/3/20
 * Time: 16:55
 */

namespace app\common;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
//https://apigateway.console.aliyun.com/?spm=a2c4g.11186623.2.13.8e325668lLd8t1#/cn-hangzhou/apis/list 网关地址
//https://market.console.aliyun.com/?#/?_k=rmkqp0 云服务地址
class Aliyun
{

    private $accessKeyId = 'LTAIIX7kpZ0hUckr';
    private $accessSecret = 'CD2ooC0swnTXaLg7bfwbYbQ3Ky0wBS';
    /**
     * 汽车行驶证文字识别接口
     */
    public function kd(){
        $url = "https://dm-53.data.aliyun.com/rest/160601/ocr/ocr_vehicle.json";
        $appcode = "8ac4b41d14ed415495c9662bbdaff312";
        $file = "./111.jpg";
        //如果输入带有inputs, 设置为True，否则设为False
        $is_old_format = false;
        //如果没有configure字段，config设为空
        $config = array(
            "side" => "face"
        );
        //$config = array()


        if($fp = fopen($file, "rb", 0)) {
            $binary = fread($fp, filesize($file)); // 文件读取
            fclose($fp);
            $base64 = base64_encode($binary); // 转码
        }
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type".":"."application/json; charset=UTF-8");
        $querys = "";
        if($is_old_format == TRUE){
            $request = array();
            $request["image"] = array(
                "dataType" => 50,
                "dataValue" => "$base64"
            );

            if(count($config) > 0){
                $request["configure"] = array(
                    "dataType" => 50,
                    "dataValue" => json_encode($config)
                );
            }
            $body = json_encode(array("inputs" => array($request)));
        }else{
            $request = array(
                "image" => "$base64"
            );
            if(count($config) > 0){
                $request["configure"] = json_encode($config);
            }
            $body = json_encode($request);
        }
        $method = "POST";
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$".$url, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
        $result = curl_exec($curl);
        $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
        $rheader = substr($result, 0, $header_size);
        $rbody = substr($result, $header_size);

        $httpCode = curl_getinfo($curl,CURLINFO_HTTP_CODE);
        if($httpCode == 200){
            if($is_old_format){
                $output = json_decode($rbody, true);
                $result_str = $output["outputs"][0]["outputValue"]["dataValue"];
            }else{
                $result_str = $rbody;
            }
            printf("result is :\n %s\n", $result_str);
        }else{
            printf("Http error code: %d\n", $httpCode);
            printf("Error msg in body: %s\n", $rbody);
            printf("header: %s\n", $rheader);
        }
    }

    /**
     * 全国快递物流查询-快递物流查询接口
     */
    public function logistics()
    {
        $host = "https://wuliu.market.alicloudapi.com";//api访问链接
        $path = "/kdi";//API访问后缀
        $method = "GET";
        $appcode = "8ac4b41d14ed415495c9662bbdaff312";//替换成自己的阿里云appcode
        $headers = array();
        //array_push($headers, "Authorization:APPCODE " . $appcode);
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $querys = "no=780098068058&type=zto";  //参数写在这里
        $bodys = "";
        $url = $host . $path . "?" . $querys;//url拼接

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        //curl_setopt($curl, CURLOPT_HEADER, true); 如不输出json, 请打开这行代码，打印调试头部状态码。
        //状态码: 200 正常；400 URL无效；401 appCode错误； 403 次数用完； 500 API网管错误
        if (1 == strpos("$" . $host, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $ret = (curl_exec($curl));
        return json_decode($ret);
        //{"status":"0","msg":"ok","result":{"number":"462587770684","type":"zto","list":[],"deliverystatus":"1","issign":"0","expName":"中通快递","expSite":"www.zto.com","expPhone":"95311","courier":"","courierPhone":""}}
    }


    public function BindAxb(){

        //composer require alibabacloud/client
        //https://api.aliyun.com/new?spm=a2c4g.11186623.2.9.72a81e82uwB6vu#/?product=Dyplsapi&api=BindAxb&params={}&tab=DEMO&lang=PHP
        // Download：https://github.com/aliyun/openapi-sdk-php
        // Usage：https://github.com/aliyun/openapi-sdk-php/blob/master/README.md
        AlibabaCloud::accessKeyClient($this->accessKeyId, $this->accessSecret)
            ->regionId('cn-hangzhou') // replace regionId as you need
            ->asDefaultClient();

//        [
//            'query' => [
//                'PhoneNoA' => "1",
//                'Expiration' => "2",
//                'PoolKey' => "3",
//                'PhoneNoB' => "1",
//                'PhoneNoX' => "2",
//                'ExpectCity' => "1",
//                'IsRecordingEnabled' => "false",
//                'OutId' => "1",
//                'OutOrderId' => "1",
//            ],
//        ]
        $options =         [
            'query' => [
                'PhoneNoA' => 15245016157,
                'Expiration' => date('Y-m-d H:i:s',time()+120),
                'PoolKey' => "FC100000069124724",
                'PhoneNoB' => 13703692716,
                'PhoneNoX' => "",
                'ExpectCity' => "",
                'IsRecordingEnabled' => "false",
                'OutId' => "1",
                'OutOrderId' => "1",
            ],
        ];
        try {

            $result = AlibabaCloud::rpc()
                ->product('Dyplsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('BindAxb')
                ->method('POST')
                ->options($options)
                ->request();
            print_r($result->toArray());
            //Array ( [Message] => isv.NO_AVAILABLE_NUMBER [RequestId] => C875C645-D19C-4F7D-B716-AC747B70E5F0 [Code] => isv.NO_AVAILABLE_NUMBER ) NULL
        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        }
    }

}